/**
 * 积分商城-主页
 */
'use strict';
import React, {
    Component
} from 'react'
import {
    Link
} from 'react-router'

import Header from './Common/Header'
import LoadingBox from './Common/LoadingBox'
import {
    HttpService,
    getLocalTime,
    jxtUrl,
    sxtUrl,
    Tips,
    addStatistics,
    hashHistory
} from '../Tools'

import '../Plugins/banner/css/banner.css'
import '../Plugins/banner/js/banner.js'
import banner from '../Img/mall/banner.png'
import banner_teacher from '../Img/mall/banner_teacher.jpg'
import banner_parent from '../Img/mall/banner_parent.jpg'
import imgBuild from '../Img/mall/build1.jpg'
import imgBuild2 from '../Img/mall/build3.gif'
import imgPk from '../Img/mall/pk2.png'
import imgErr from '../Img/other/splitImg.jpg'

export default class Integral extends Component {
    constructor(props) {
        super(props);
        this.page = 1;
        this.pagesize = 10;
        this.toBottom = 60;
        this.onload = 0
        this.state = {
            integral: 0,
            dataList: [],
            bannerList: [],
            dataLoad: 1,
            dataNull: 0,
            dataEnd: 0
        }
        this.wherefrom = 'share'
        if (sessionStorage.app == 'true')
            this.wherefrom = 'app'
        if (sessionStorage.weixin == 'true')
            this.wherefrom = 'weixin'
    }
    componentWillMount() {
        this.getBanner();
        this.getData()
        this.getIntegral()
    }
    componentWillUnmount() {
        clearInterval(sessionStorage.timer);
    }
    componentDidMount() {
        //加载更多
        window.onscroll = () => {
            const {
                dataEnd,
                dataNull,
                page
            } = this.state;
            if (this.dataLoad == 1 || dataEnd == 1 || dataNull == 1)
                return;
            var scrollTop = 0;
            if (document.documentElement && document.documentElement.scrollTop) {
                scrollTop = document.documentElement.scrollTop;
            } else if (document.body) {
                scrollTop = document.body.scrollTop;
            }
            if (document.body.clientHeight - window.innerHeight - scrollTop <= this.toBottom) {
                this.page++;
                this.getData();
            }
        }
    }

    //图片地址错误
    imgErr(e) {
        e.currentTarget.setAttribute('src', imgErr)
    }

    //查询商品
    getData() {
        this.dataLoad = 1
        let data = {
            token: sessionStorage.appToken,
            page: this.page,
            size: this.pagesize,
            range: sessionStorage.userrole == '家长' ? 2 : 1
        };
        if (sessionStorage.userrole == '家长')
            data.babyid = sessionStorage.babyid
        HttpService.query({
            // url: '/src/Data/integral/goodsData.json',
            url: '/jf/company/pageJfCompanyArch',
            data,
            success: (res => {
                this.dataLoad = 0
                this.onload = 1
                this.setState({
                    dataLoad: 0
                });
                // setTimeout(() => {
                //     if ($('.product_list').length == 0 && this.onload == 1) {
                //         $('#nogoods').show()
                //     }
                // }, 600)
                if (res.code == 10140) {
                    //获取数据成功
                    let dataList = res.data.list
                    if (status != 1)
                        dataList = this.state.dataList.concat(res.data.list);
                    this.setState({
                        dataList
                    });
                    if (res.data.total == this.pagesize) {
                        this.setState({
                            dataEnd: 1
                        });
                    } else if (res.data.list.length < this.pagesize) {
                        this.setState({
                            dataEnd: 1
                        });
                        if (dataList.length == 0) {
                            this.setState({
                                dataEnd: 0
                                // dataNull: 1
                            });
                        }
                    }
                    return;
                }
                this.setState({
                    dataEnd: 1
                });
                Tips(res.msg);
            })
        })
    }

    //查询积分
    getIntegral() {
        if (!sessionStorage.appToken)
            return
        HttpService.query({
            url: `/${sessionStorage.userrole=='家长'?'guardian':'teacherapp'}/credit/getCurrentCredits`,
            data: {
                token: sessionStorage.appToken,
                type: 1
            },
            success: (res => {
                if (res.code == 20014) {
                    this.setState({
                        integral: res.data.overplusCredit
                    })
                    return
                }
                Tips(res.msg)
            })
        })
    }

    //获取banner数据
    getBanner() {
        let rct = this;
        $.ajax({
            url: `${sxtUrl}/banner/listBanner?bannerRange=${sessionStorage.userrole=='家长'?3:2}`,
            success: function(res) {
                if (res.code == 10140) {
                    if (res.data.length == 0) {
                        $('.banner2 .position').css('opacity', 1)
                        return
                    }
                    if (res.data.length == 1) {
                        let item = res.data[0];
                        $('.banner2 .position').attr('src', item.bannerUrl).css('opacity', 1).click(function() {
                            let tolink = `${jxtUrl}/jiaxiaotong/#/InfoDetail/${item.id}/${rct.wherefrom}/banner/true?${localStorage.jxtUrlData}`
                            if (item.displayType == 2 && item.displayContent)
                                tolink = `#/iframe/share/${encodeURIComponent(item.theme)}/${encodeURIComponent(item.displayContent)}`
                            location.href = tolink
                        })
                        return
                    }
                    rct.setState({
                        bannerList: res.data
                    })
                    //添加序号
                    $('.banner .status').empty();
                    for (var i = 1; i <= $('.banner li').length; i++) {
                        $('.banner .status').append('<a></a>');
                    }
                    //调用轮播
                    $(".imgs").touchSlider({
                        flexible: true,
                        speed: 500,
                        btn_prev: $(".btn_prev"),
                        btn_next: $(".btn_next"),
                        paging: $(".status a"),
                        counter: function(e) {
                            $(".status a").removeClass("active").eq(e.current - 1).addClass("active");
                        }
                    });

                    //自动滚动
                    clearInterval(sessionStorage.timer);
                    sessionStorage.timer = setInterval(() => {
                        $(".btn_next").click();
                    }, 5000);
                    //滑动事件关闭定时器
                    $(".banner").bind("touchstart", function() {
                        clearInterval(sessionStorage.timer);
                    }).bind("touchend", function() {
                        clearInterval(sessionStorage.timer);
                        sessionStorage.timer = setInterval(function() {
                            $(".btn_next").click();
                        }, 5000);
                    });
                } else {
                    Tips(res.msg)
                    $('.banner .position').css('opacity', 1)
                }
            }
        })
    }

    //百度统计
    baiduStatistics(index) {
        addStatistics('/banner/getCreditBanner')
        _hmt.push(['_trackEvent', 'page', 'integral', `Banner${++index}点击量`]);
    }

    render() {
        const userrole = sessionStorage.userrole
        let bannerSrc = userrole == '家长' ? banner_parent : banner_teacher
        let unit = userrole == '家长' ? '积分' : '荣誉值';
        const {
            dataList,
            dataLoad,
            dataNull,
            dataEnd,
            bannerList,
            integral
        } = this.state
        const goodsDataTag = dataList.map((item, index) => {
            if (!item.listGoods)
                return
            let goodsTag = item.listGoods.map((good, index) => {
                let url = imgErr,
                    sign = 'sign '; //1:惠，2券，3团，4亲
                if (good.smallImg.indexOf('{') > -1)
                    url = JSON.parse(good.smallImg).goodsHeaderImg

                switch (good.cardProperty) {
                    case 1:
                        sign += 'hui'
                        break;
                    case 2:
                        sign += 'quan'
                        break;
                    default:
                }
                return (
                    <li>
                        <span className={sign}></span>
                        <span className="punkte"><i>{good.consumeCredit}</i>{unit}</span>
                        <span className="name">{good.name}</span>
                    </li>
                )
            })
            return (
                <Link className='bns_item' to={'/companyInfo/'+item.id}>
                    {index==0&&item.top>0?<hot />:null}
                    <img src={item.logo} onError={this.imgErr.bind(this)} />
                    <h5>{item.name}</h5>
                    <p>{item.businessType} {item.address.split('-')[1]} {item.address.split('-')[2]}</p>
                    <ul className='clearfix'>
                        {goodsTag}
                    </ul>
                </Link>
            )
        })
        const bannerTagList = bannerList.map((item, index) => {
            let tolink = `${jxtUrl}/jiaxiaotong/#/InfoDetail/${item.id}/${this.wherefrom}/banner/false?${localStorage.jxtUrlData}`
            if (item.displayType == 2 && item.displayContent)
                tolink = `#/iframe/share/${encodeURIComponent(item.theme)}/${encodeURIComponent(item.displayContent)}`

            return (
                <li onClick={this.baiduStatistics.bind(this,index)}>
                    <a href={tolink}>
                        <img src={item.bannerUrl} />
                    </a>
                </li>
            )
        });
        return (
            <div className="punkte_mall">
                <Header title={userrole=='家长'?'快乐城堡':'园丁园'} outLink={sessionStorage.app=='true'?'/appback':null} />
                <div className={bannerList.length==0?'banner2':'banner'}>
                    <div className="status"></div>
                    <div className="imgs">
                        <img src={bannerSrc} className="position" />
                        <ul>
                            {bannerTagList}
                        </ul>
                        <a className="btncommon btn_prev"></a>
                        <a className="btncommon btn_next"></a>
                    </div>
                </div>
                <div className="mall_header">
                    <Link to="/IntegralMyself">
                        <span className="img surplus"><i>{unit}</i></span>
                        <span><span className="punkte">{integral}</span></span>
                    </Link>
                    <Link to="/TaskToday">
                        <span className="img earn"></span>
                        <span>赚{unit}</span>
                    </Link>
                    <Link to="/Umtauschen">
                        <span className="img exchange"></span>
                        <span>兑换记录</span>
                    </Link>
                    <Link to="/MyPackage">
                        <span className="img package"></span>
                        <span>我的卡券</span>
                    </Link>
                </div>
                <div>
                    <div className="business_list">
                        {goodsDataTag}
                    </div>
                    <LoadingBox dataLoad={dataLoad} dataNull={dataNull} dataEnd={dataEnd} />
                </div>
                {dataList.length>0?<div id='nogoods' className="banner text-center bgc-white hidden" style={{marginBottom:0,marginTop:'1px',padding:'10px'}}>
                    <img src={sessionStorage.userrole=='家长'?imgBuild:imgBuild2}/>
                </div>:null}

            </div>
        )
    }
}
